import React, { useRef } from "react";
import PickerPanel from "../components/picker-panel";
import Picker from "../components/picker-view";
import useOverlay from "./useOverlay";
import { PickerHookProps } from "../../types/uses/usePicker";


function usePicker<T>() {
  const overlay = useOverlay();
  const pickerValueRef = useRef([] as any);
  const show = function(props: PickerHookProps<T>) {
    return overlay.show(
      () => {
        return (
          <PickerPanel
            {...props}
            title={props.title}
            onCancel={() => {
              overlay.close();
              props.onCancel?.()
              pickerValueRef.current = null;
            }}
            onConfirm={() => {
              overlay.close();
              props.onConfirm && props.onConfirm(pickerValueRef.current);
              pickerValueRef.current = null;
            }}
          >
            <Picker<T>
              {...props}
              onChange={value => {
                pickerValueRef.current = [...value];
              }}
            />
          </PickerPanel>
        );
      },
      {
        type: "slid-up"
      }
    );
  };
  return { ...overlay, show };
}

export default usePicker;
